<style lang="less">
@import '../../../styles/table-common.less';
@import '../../personInfo.less';
.ivu-card-head {
    background: #378cfe;
    padding: 15px !important;

    .head-name {
        color: #fff;
    }

    .ivu-dropdown {
        a {
            color: #fff;
        }

        .light-text {
            color: #378cfe;
            border: none !important;
        }
    }
}
</style>
<template>
    <div class="search">
        <!--      <div slot="title">-->
        <!--        <div class="edit-head">-->
        <!--          <div class="head-name" style="text-align: center; flex-grow: 1; font-weight: bold; font-size: 1.4em">-->
        <!--            {{currVersion}}地区代码版本库-->
        <!--          </div>-->
        <!--          <Dropdown @on-click="versDropdown">-->
        <!--            <a href="javascript:void(0)">-->
        <!--              切换版本-->
        <!--              <Icon type="ios-arrow-down"></Icon>-->
        <!--            </a>-->
        <!--            <template #list>-->
        <!--              <DropdownMenu>-->
        <!--                <DropdownItem name="addVers" class="light-text">添加版本库</DropdownItem>-->
        <!--                <DropdownItem :name="option" v-for="option in versionList">{{ option }}版</DropdownItem>-->
        <!--              </DropdownMenu>-->
        <!--            </template>-->
        <!--          </Dropdown>-->
        <!--        </div>-->
        <!--      </div>-->
        <Row :gutter="16" class="all-height">
            <Col :span="showRight ? 18 : 24" class="all-height">
                <Card class="all-height card-child-height">
                    <Row class="operation code-row-bg" style="display: flex; justify-content: space-between">
                        <Col span="22">
                            <Button v-has="'add'" @click="add" type="primary" icon="md-add">添加</Button>
                            <Button v-has="'delete'" @click="delAll" icon="md-trash">批量删除</Button>
                            <Button @click="getDataList" icon="md-refresh">刷新</Button>
                            <Button v-has="'input'" @click="dropImportData">导入地区代码数据</Button>
                            <!--        <Button type="dashed" @click="openSearch=!openSearch">{{ openSearch ? "关闭搜索" : "开启搜索" }}</Button>-->
                            <Button type="dashed" @click="openTip = !openTip">{{ openTip ? '关闭提示' : '开启提示' }}</Button>
                        </Col>
                        <Col span="2" style="text-align: right">
                            <Icon
                                color="#fff"
                                class="icon01"
                                :type="showRight ? `ios-arrow-forward` : `ios-arrow-back`"
                                @click.native="clickShowRight"
                            ></Icon>

                            <!--              <Button :icon="showRight?`ios-arrow-forward`:`ios-arrow-back`"-->
                            <!--                      @click.native="clickShowRight"-->
                            <!--                      type="primary">-->
                            <!--              </Button>-->
                        </Col>
                    </Row>

                    <Row v-show="openTip">
                        <Alert show-icon>
                            已选择
                            <span class="select-count">{{ selectList.length }}</span>
                            项
                            <a class="select-clear" @click="clearSelectAll">清空</a>
                        </Alert>
                    </Row>
                    <Row class="calc-px-height">
                        <Table
                            :loading="loading"
                            border
                            :columns="columns"
                            :data="data"
                            ref="table"
                            sortable="custom"
                            :height="height1"
                            @on-sort-change="changeSort"
                            @on-selection-change="changeSelect"
                            @on-row-dblclick="sjclaib"
                        ></Table>
                    </Row>
                    <Row type="flex" justify="end" class="page">
                        <Page
                            :current="searchForm.pageNumber"
                            :total="total"
                            :page-size="searchForm.pageSize"
                            @on-change="changePage"
                            @on-page-size-change="changePageSize"
                            :page-size-opts="[10, 20, 50, 100, 200]"
                            size="small"
                            show-total
                            show-elevator
                            show-sizer
                        ></Page>
                    </Row>
                </Card>
            </Col>
            <Col span="6" class="all-height" v-show="showRight">
                <Card class="all-height card-child-height">
                    <Row v-show="!modalVisible" @keydown.enter.native="handleSearch">
                        <Col span="24">
                            <div class="drawer-header">
                                <div class="cmr16">查询区</div>
                            </div>
                        </Col>
                        <Col span="24">
                            <Form ref="searchForm" :model="searchForm" :label-width="labelWidth100">
                                <FormItem label="地区代码" prop="code">
                                    <Input type="text" v-model="searchForm.code" placeholder="请输入地区代码" clearable style="width: 100%" />
                                </FormItem>
                                <FormItem label="地区名称" prop="name">
                                    <Input type="text" v-model="searchForm.name" placeholder="请输入地区名称" clearable style="width: 100%" />
                                </FormItem>
                                <span v-if="drop">
                                    <FormItem label="显示名称" prop="displayName">
                                        <Input type="text" v-model="searchForm.displayName" placeholder="请输入显示名称" clearable style="width: 100%" />
                                    </FormItem>
                                    <FormItem label="地区类型代码" prop="typeCode">
                                        <Input type="text" v-model="searchForm.typeCode" placeholder="请输入地区类型代码" clearable style="width: 100%" />
                                    </FormItem>
                                    <FormItem label="地区类型名称" prop="typeName">
                                        <Input type="text" v-model="searchForm.typeName" placeholder="请输入地区类型名称" clearable style="width: 100%" />
                                    </FormItem>
                                </span>
                                <FormItem  class="br ">
                                    <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                    <Button @click="handleReset">重置</Button>
                                    <a class="drop-down" @click="dropDown">
                                        {{ dropDownContent }}
                                        <Icon :type="dropDownIcon"></Icon>
                                    </a>
                                </FormItem>
                            </Form>
                        </Col>
                    </Row>
                    <Row v-show="modalVisible" style="flex-direction: column">
                        <div class="drawer-header">
                            <div class="cmr16">{{ modalTitle }}</div>
                        </div>
                        <Form ref="form" :model="form" :rules="formValidate" :label-width="labelWidth120" label-position="right">
                            <FormItem label="地区代码" prop="code">
                                <Input v-model="form.code" clearable />
                            </FormItem>
                            <FormItem label="地区名称" prop="name">
                                <Input v-model="form.name" clearable />
                            </FormItem>
                            <FormItem label="显示名称" prop="displayName">
                                <Input v-model="form.displayName" clearable />
                            </FormItem>
                            <FormItem label="地区类型代码" prop="typeCode">
                                <Input v-model="form.typeCode" clearable />
                            </FormItem>
                            <FormItem label="地区类型名称" prop="typeName">
                                <Input v-model="form.typeName" clearable />
                            </FormItem>
                        </Form>
                        <div class="br right-bottom-edit">
                            <Button type="text" @click="modalVisible = false">取消</Button>
                            <div v-if="modalType == 0" style="display: inline">
                                <Button v-has="'add'" type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
                            </div>
                            <div v-if="modalType == 1" style="display: inline">
                                <Button v-has="'edit'" type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
                            </div>
                        </div>
                    </Row>
                </Card>
            </Col>
        </Row>

        <!--    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="500">-->

        <!--    </Modal>-->

        <Drawer title="导入数据" closable v-model="importModalVisible" class="c-drawer02">
            <div style="display: flex; justify-content: space-between; align-items: center">
                <Upload action :before-upload="beforeUploadImport" accept=".xls, .xlsx">
                    <Button :loading="reading" icon="ios-cloud-upload-outline" style="margin-right: 10px">上传Excel文件</Button>
                    <span v-if="uploadFile.name">当前选择文件：{{ uploadFile.name }}</span>
                </Upload>
                <Button @click="clearImportData" icon="md-trash">清空数据</Button>
            </div>
            <Alert type="warning" show-icon>导入前请下载查看导入模版数据文件查看所需字段及说明，确保数据格式正确，不得修改列英文名称</Alert>
            <Table :columns="importColumns" border :height="height" :data="importTableData" ref="importTable"></Table>
            <div class="drawer-footer">
                <Button @click="downloadTemple" type="info">下载导入模板</Button>
                <div style="position: absolute; right: 15px; display: inline-block">
                    <Button @click="importModalVisible = false">关闭</Button>
                    <Button :loading="importLoading" :disabled="importTableData.length <= 0" @click="importData" style="margin-left: 8px" type="primary">
                        确认导入
                        <span v-if="importTableData.length > 0">{{ importTableData.length }} 条数据</span>
                    </Button>
                </div>
            </div>
        </Drawer>
    </div>
</template>

<script>
import { shortcuts } from '@/libs/shortcuts';
import excel from '@/libs/excel';
import { postBodyRequest } from '@/libs/axios';

export default {
    name: 'areaCode',
    components: {},
    data() {
        return {
            labelWidth120: 120,
            labelWidth100: 100,
            currVersion: '',
            versionList: [],
            height: 510,
            openSearch: true, // 显示搜索
            openTip: true, // 显示提示
            importLoading: false,
            loading: true, // 表单加载状态
            modalType: 0, // 添加或编辑标识
            modalVisible: false, // 添加或编辑显示
            modalTitle: '', // 添加或编辑标题
            drop: false,
            importModalVisible: false,
            dropDownContent: '展开',
            dropDownIcon: 'ios-arrow-down',
            height1: 0,
            searchForm: {
                // 搜索框初始化对象
                pageNumber: 1, // 当前页数
                pageSize: 50, // 页面大小
                sort: 'createTime', // 默认排序字段
                order: 'desc' // 默认排序方式
            },
            form: {
                // 添加或编辑表单对象初始化数据
                code: '',
                name: '',
                displayName: '',
                typeCode: '',
                typeName: ''
            },
            // 表单验证规则
            formValidate: {
                code: [{ required: true, message: '不能为空', trigger: 'change' }],
                name: [{ required: true, message: '不能为空', trigger: 'change' }],
                typeCode: [{ required: true, message: '不能为空', trigger: 'change' }],
                typeName: [{ required: true, message: '不能为空', trigger: 'change' }]
            },
            submitLoading: false, // 添加或编辑提交状态
            selectList: [], // 多选数据
            columns: [],
            columns_1: Object.freeze([
                // 表头
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    title: '序号',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '地区代码',
                    key: 'code',
                    minWidth: 80,
                    sortable: false
                },
                {
                    title: '地区名称',
                    key: 'name',
                    minWidth: 160,
                    sortable: false
                },
                {
                    title: '显示名称',
                    key: 'displayName',
                    minWidth: 160,
                    sortable: false
                },
                {
                    title: '地区类型代码',
                    key: 'typeCode',
                    minWidth: 120,
                    sortable: false
                },
                {
                    title: '地区类型名称',
                    key: 'typeName',
                    minWidth: 120,
                    sortable: false
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    minWidth: 120,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'edit') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.row);
                                        }
                                    }
                                },
                                '编辑'
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                }
                            }),
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'delete') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row);
                                        }
                                    }
                                },
                                '删除'
                            )
                        ]);
                    }
                }
            ]),
            importTableData: [],
            importColumns: [],
            uploadFile: {
                name: ''
            },
            data: [], // 表单数据
            total: 0, // 表单数据总数
            showRight: true
        };
    },
    methods: {
        tableheig() {
            var bbb = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
            var aaa = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[1];
            var ccc = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[0].scrollHeight;
            var ddd = bbb - ccc;
            console.log(bbb, '00000000000000');
            aaa.style.height = `${ddd}px`;

            if (this.searchForm.pageSize === 10) {
                this.height1 = 0;
            } else {
                this.height1 = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
                if (this.total < this.searchForm.pageNumber * this.searchForm.pageSize) {
                    var r = (this.searchForm.pageNumber - 1) * this.searchForm.pageSize;
                    var a = this.total - r;
                    var s = a * 43 + 65;
                    if (s < this.height1) {
                        this.height1 = 0;
                    }
                }
            }
            if (this.total < 10) {
                this.height1 = 0;
            }
        },
        init() {
            this.getVersionListInit();
            this.getDataList();
        },
        // 显示隐藏右侧区域
        clickShowRight() {
            this.showRight = !this.showRight;
        },
        changePage(v) {
            this.searchForm.pageNumber = v;
            this.getDataList();
            this.clearSelectAll();
        },
        changePageSize(v) {
            this.searchForm.pageSize = v;
            this.getDataList();
        },
        handleSearch() {
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            this.getDataList();
        },
        handleReset() {
            this.$refs.searchForm.resetFields();
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            // 重新加载数据
            this.getDataList();
        },
        changeSort(e) {
            this.searchForm.sort = e.key;
            this.searchForm.order = e.order;
            if (e.order === 'normal') {
                this.searchForm.order = '';
            }
            this.getDataList();
        },
        clearSelectAll() {
            this.$refs.table.selectAll(false);
        },
        changeSelect(e) {
            this.selectList = e;
        },
        dropDown() {
            if (this.drop) {
                this.dropDownContent = '展开';
                this.dropDownIcon = 'ios-arrow-down';
            } else {
                this.dropDownContent = '收起';
                this.dropDownIcon = 'ios-arrow-up';
            }
            this.drop = !this.drop;
        },
        getDataList() {
            this.loading = true;
            this.searchForm.version = this.currVersion;
            // 带多条件搜索参数获取表单数据 请自行修改接口
            this.postRequest('/areaCode/getByPage', this.searchForm).then(res => {
                this.loading = false;
                if (res.success) {
                    this.data = res.result.records;
                    this.total = res.result.total;
                    this.tableheig();
                    if (this.data.length == 0 && this.searchForm.pageNumber > 1) {
                        this.searchForm.pageNumber -= 1;
                        this.getDataList();
                    }
                }
            });
        },
        handleSubmit() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    if (this.modalType === 0) {
                        // 添加 避免编辑后传入id等数据 记得删除
                        delete this.form.id;
                        this.form.version = this.currVersion;
                        this.postRequest('/areaCode/insertOrUpdate', this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.getDataList();
                                this.modalVisible = false;
                            }
                        });
                    } else {
                        // 编辑
                        this.postRequest('/areaCode/insertOrUpdate', this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.getDataList();
                                this.modalVisible = false;
                            }
                        });
                    }
                }
            });
        },
        add() {
            this.modalType = 0;
            this.modalTitle = '添加';
            this.$refs.form.resetFields();
            delete this.form.id;
            this.form.version = this.currVersion;
            this.modalVisible = true;
        },
        sjclaib(v) {
            this.showRight = true;
            this.modalType = 1;
            this.modalTitle = '编辑';
            this.$refs.form.resetFields();
            // 转换null为""
            for (let attr in v) {
                if (v[attr] === null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.modalVisible = true;
        },
        edit(v) {
            this.modalType = 1;
            this.modalTitle = '编辑';
            this.$refs.form.resetFields();
            // 转换null为""
            for (let attr in v) {
                if (v[attr] === null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.modalVisible = true;
        },
        remove(v) {
            let param = {
                ids: v.id
            };
            this.$Modal.confirm({
                title: '确认删除',
                // 记得确认修改此处
                content: '您确认要删除该条数据?',
                loading: true,
                onOk: () => {
                    // 删除
                    this.postRequest('/areaCode/delByIds', param).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                }
            });
        },
        delAll() {
            if (this.selectList.length <= 0) {
                this.$Message.warning('您还未选择要删除的数据');
                return;
            }
            this.$Modal.confirm({
                title: '确认删除',
                content: '您确认要删除所选的 ' + this.selectList.length + ' 条数据?',
                loading: true,
                onOk: () => {
                    let ids = '';
                    this.selectList.forEach(function (e) {
                        ids += e.id + ',';
                    });
                    ids = ids.substring(0, ids.length - 1);
                    // 批量删除
                    this.postRequest('/areaCode/delByIds', { ids: ids }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                }
            });
        },
        //导入地区代码数据
        dropImportData() {
            this.importModalVisible = true;
        },
        beforeUploadImport(file) {
            this.uploadFile = file;
            const fileExt = file.name.split('.').pop().toLocaleLowerCase();
            if (fileExt == 'xlsx' || fileExt == 'xls') {
                this.readFile(file);
                this.file = file;
            } else {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc: '所选文件‘ ' + file.name + ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
                });
            }
            return false;
        },
        // 读取文件
        readFile(file) {
            this.reading = true;
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onerror = e => {
                this.reading = false;
                // this.$Message.error("文件读取出错");
                this.$Message.error({
                    content: '文件读取出错',
                    duration: 5,
                    closable: true
                });
            };
            reader.onload = e => {
                const data = e.target.result;
                const { header, results } = excel.read(data, 'array');
                const tableTitle = header.map(item => {
                    return { title: item, key: item, minWidth: 130, align: 'center' };
                });
                this.importTableData = results;
                this.importColumns = tableTitle;
                this.reading = false;
                this.$Message.success('读取数据成功');
            };
        },
        clearImportData() {
            this.importTableData = [];
            this.importColumns = [];
            this.uploadfile = {};
        },
        downloadTemple() {
            // 直接放入excel文件当作模板
            // alert(process.env.BASE_URL + "地区代码导入模板.xlsx", "process.env.BASE_URL + \"用户导入模板.xlsx\"")
            window.location.href = process.env.BASE_URL + '地区代码导入模板.xlsx';
        },
        importData() {
            let params = this.importTableData.map(item => {
                return {
                    code: item['地区代码'],
                    name: item['地区名称'],
                    displayName: item['显示名称'],
                    typeCode: item['地区类型代码'],
                    typeName: item['地区类型名称'],
                    version: this.currVersion
                };
            });
            this.importLoading = true;
            postBodyRequest('/areaCode/importData', params).then(res => {
                this.importLoading = false;
                if (res.success) {
                    this.importModalVisible = false;
                    this.getDataList();
                    this.$Modal.info({
                        title: '导入结果',
                        content: res.message
                    });
                }
            });
        },
        versDropdown(name) {
            if (name === 'addVers') {
                this.currVersion = parseInt(this.versionList[0]) + 1;
                const nextYear = new Date().getFullYear() + 1;
                if (parseInt(this.currVersion) > nextYear) {
                    this.currVersion = nextYear;
                }
                this.$Message.warning('您只能添加' + parseInt(this.currVersion) + '年的专业代码版本！');
            } else {
                this.currVersion = name;
            }
            this.getDataList();
        },
        getVersionListInit() {
            this.postRequest('/areaCode/getVersions').then(res => {
                if (res.success) {
                    this.versionList = res.result;
                    this.currVersion = this.versionList[0];
                }
            });
        },
        onRestWindow() {
            this.columns = this.restTableCellWidth(this.columns_1)
            this.labelWidth120 = this.searchLabelWidth(this.labelWidth120)
            this.labelWidth100 = this.searchLabelWidth(this.labelWidth100)
        }
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)
        this.init();
    },
    beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
    }
};
</script>
<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
// @import "../../../styles/table-common.less";
.search {
    .operation {
        margin-bottom: 2vh;
    }

    .select-count {
        font-weight: 600;
        color: #40a9ff;
    }

    .select-clear {
        margin-left: 10px;
    }

    .page {
        margin-top: 2vh;
    }

    .drop-down {
        margin-left: 5px;
    }
}
//.edit-head {
//  display: flex;
//  justify-content: space-between;
//  align-items: center;
//}
//.light-text {
//  color: #9ff8cf;
//  border: 1px solid #ccc;
//  padding: 5px;
//  border-radius: 4px;
//}
</style>

<style lang="less" scoped>
.icon01 {
    background: rgb(45, 154, 244); border-radius: 50%; padding: 3px
}
.cmr16{
    margin-right: 16px
}
.cmr10 {
    margin-right: 10px 
}
.cml-35 {
    margin-left: -35px;
}
.c-drawer02 {
    /deep/ .ivu-drawer {
        width:1000px !important;
    }
    
}
</style>
